package com.wj.book.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wj.book.pojo.Book;
import com.wj.book.service.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class BookController {

    @Autowired
    BookServiceImpl bookService;

//    @GetMapping("/books")
//    public ModelAndView findAllBooks() {
//        List<Book> books = bookService.findAllBooks();
//        ModelAndView mv = new ModelAndView();
//        mv.addObject("books", books);
//        mv.setViewName("booklist");
//        return mv;
//    }

    @GetMapping("/booksPage")
    public ModelAndView booksPage(@RequestParam(value="start",defaultValue = "1")int start,
                                  @RequestParam(value="size",defaultValue = "3") int size){ //默认查询第1页，每页显示3条
        PageHelper.startPage(start,size,"id asc"); //表示起始页为start每页显示size条根据id升序排序进行分页
        List<Book> books=bookService.findAllBooks();
        PageInfo<Book> page=new PageInfo<>(books);
        ModelAndView mv=new ModelAndView();
        mv.addObject("page",page);
        mv.setViewName("booklist");
        return mv;
    }

    @GetMapping("/book/{id}")
    public ModelAndView findBookById(@PathVariable int id) {
        Book book = bookService.finBookById(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("book", book);
        mv.setViewName("bookdetail");
        return mv;
    }

    @PostMapping("/addBook")
    public ModelAndView addBook(Book book) {
        bookService.addBook(book);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/booksPage");
        return mv;
    }

    @GetMapping("/addBook")
    public String addBook() {
        return "addbook";
    }

    @GetMapping("/deleteBook")
    public ModelAndView deleteBook(int id) {
        bookService.deleteBook(id);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/booksPage");
        return mv;
    }


    @PostMapping("/updateBook")
    public ModelAndView updateBook(Book book) {
        bookService.updateBook(book);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/booksPage");
        return mv;
    }

    @GetMapping("/toUpdateBook")
    public ModelAndView toUpdateBook(int id) {
        Book book = bookService.finBookById(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("book", book);
        mv.setViewName("updateBook");
        return mv;
    }
}
